//
//  FilePreView.swift
//  miaoyin
//
//  Created by David on 2017/3/10.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit
import QuickLook


@objc protocol CardViewDelegate {
    @objc optional func cardViewClose(_ cardView: UIView)
}

@objc protocol FileUploadDelegate {
    @objc optional func fileUpload(_ fileView: FilePreView, failUpload message: Any?)
    @objc optional func fileUpload(_ fileView: FilePreView, successUpload message: Any?)
    @objc optional func fileUpload(_ fileView: FilePreView, gotoFileView file: Any?)
    @objc optional func fileUpload(_ fileView: FilePreView, askBeforeExit alert: UIAlertController)
}

class FilePreView: UIView, QLPreviewControllerDelegate, QLPreviewControllerDataSource, URLSessionDataDelegate {

    var firstShow = true
    
    var delegate: CardViewDelegate?
    var uploadDelegate: FileUploadDelegate?
    
    var docVC: QLPreviewController!
    
    var titleLabel: UILabel!
    
    var uploadBtn: UIButton!
    
    var uploadTask: URLSessionDataTask?
    var progressBar: UIProgressView!
    
    var finishBtn: UIButton!
    
    init(frame: CGRect, vc: UIViewController) {
        super.init(frame: frame)
        let bgView = UIVisualEffectView(frame: frame)
        bgView.effect = UIBlurEffect(style: .dark)
        addSubview(bgView)
        
//        let blankCloseBtn = UIButton(frame: frame)
//        bgView.addSubview(blankCloseBtn)
//        blankCloseBtn.addTarget(self, action: #selector(FilePreView.hideView), for: .touchUpInside)

        
        
        let cardView = UIView(frame: CGRect(x: 32, y: 0, width: frame.width - 32, height: frame.height - 128))
        cardView.center = CGPoint(x: frame.width/2, y: frame.height/2)
        cardView.backgroundColor = UIColor.white
        cardView.layer.cornerRadius = 8
        cardView.layer.masksToBounds = true
        bgView.addSubview(cardView)
        
        let titleBar = UIView(frame: CGRect(x: 0, y: 0, width: cardView.frame.width, height: 44))
        cardView.addSubview(titleBar)
        
        let closeBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        closeBtn.setTitle("×", for: .normal)
        closeBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24)
        closeBtn.setTitleColor(themeColor2, for: .normal)
        titleBar.addSubview(closeBtn)
        closeBtn.addTarget(self, action: #selector(FilePreView.hideView), for: .touchUpInside)
        
        titleLabel = UILabel(frame: CGRect(x: 52, y: 0, width: cardView.frame.width - 44 - 24, height: 44))
        titleLabel.text = "文件"
        titleLabel.textAlignment = .center
        titleLabel.lineBreakMode = .byTruncatingMiddle
        titleBar.addSubview(titleLabel)
        
        fileURL = URL(string: "file://\(DOCUMENT_PATH)/file.doc")
        
        docVC = QLPreviewController()
        docVC.delegate = self
        docVC.dataSource = self
        vc.addChildViewController(docVC)
        docVC.view.frame = CGRect(x: 0, y: 44, width: cardView.frame.width, height: cardView.frame.height - 52)
        cardView.addSubview(docVC.view)
        docVC.didMove(toParentViewController: vc)
        
        uploadBtn = UIButton(frame: CGRect(x: 0, y: cardView.frame.height - 44, width: cardView.frame.width, height: 44))
        uploadBtn.backgroundColor = themeColor1
//        uploadBtn.layer.cornerRadius = 8
        uploadBtn.setTitle("上传文件", for: .normal)
        uploadBtn.setTitleColor(UIColor.white, for: .normal)
        uploadBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        uploadBtn.alpha = 0
        cardView.addSubview(uploadBtn)
        uploadBtn.addTarget(self, action: #selector(FilePreView.uploadFile), for: .touchUpInside)
        
//        let docVC = QLPreviewController()
//        docVC.delegate = self
//        docVC.dataSource = self
//        addChildViewController(docVC)
//        docVC.view.frame = CGRect(x: 0, y: 0, width: preView.frame.width, height: preView.frame.height)
//        preView.addSubview(docVC.view)
//        docVC.didMove(toParentViewController: self)
        
        progressBar = UIProgressView(progressViewStyle: .default)
        progressBar.frame = CGRect(x: 16, y: 0, width: cardView.frame.width - 32, height: 2)
        progressBar.center.y = uploadBtn.center.y
        progressBar.tintColor = themeColor1
        cardView.addSubview(progressBar)
        progressBar.alpha = 0
        
        finishBtn = UIButton(frame: CGRect(x: 0, y: cardView.frame.height - 44, width: cardView.frame.width, height: 44))
        finishBtn.backgroundColor = themeColor1
        finishBtn.setTitle("关闭", for: .normal)
        finishBtn.setTitleColor(UIColor.white, for: .normal)
        finishBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        finishBtn.alpha = 0
        cardView.addSubview(finishBtn)
        finishBtn.addTarget(self, action: #selector(FilePreView.gotoFileView), for: .touchUpInside)
        
        alpha = 0
    }
    
    var fileURL: URL?
    
    func openFile(url: URL?){
        if url == nil{
            return
        }
        
        let decodedURL = url?.absoluteString.removingPercentEncoding
        let fileName = decodedURL?.components(separatedBy: "/").last
        titleLabel.text = fileName ?? "文件"
        
        
        
        if isLogin(){
            uploadBtn.alpha = 1
            uploadBtn.setTitle("上传文件", for: .normal)
            uploadBtn.isEnabled = true
            if firstShow{
                let docFrame = docVC.view.frame
                docVC.view.frame = CGRect(origin: docFrame.origin, size: CGSize(width: docFrame.width, height: docFrame.height - 32))
                firstShow = false
            }
            
        }else{
            uploadBtn.alpha = 0
            if !firstShow {
                let docFrame = docVC.view.frame
                docVC.view.frame = CGRect(origin: docFrame.origin, size: CGSize(width: docFrame.width, height: docFrame.height + 32))
                firstShow = true
            }
        }
        fileURL = url
//        bringSubview(toFront: docVC.view)
        docVC.reloadData()
        docVC.currentPreviewItemIndex = 0
        docVC.refreshCurrentPreviewItem()
        
        
        progressBar.alpha = 0
        finishBtn.alpha = 0
        
        do{
            var path = fileURL?.absoluteString.removingPercentEncoding
            path = path?.replacingOccurrences(of: "file://", with: "")
            print(path ?? "path nil")
            if path != nil{
                let type = path?.components(separatedBy: ".").last
                
                if type == "ppt" || type == "pptx" {
                    let attr = try FileManager.default.attributesOfItem(atPath: path!)
                    print(attr)
                    let size = attr[FileAttributeKey.size] as? Double
                    if size != nil{
                        if size! > 2097152 {
                            uploadBtn.isEnabled = false
                            uploadBtn.setTitle("抱歉, 暂不支持大于2M的ppt文件", for: .normal)
                        }
                    }else{
                        uploadBtn.isEnabled = false
                        uploadBtn.setTitle("抱歉, 暂不支持大于2M的ppt文件", for: .normal)
                    }
                }
                
                
            }
        }catch let ex{
            print(ex)
        }
        
        UIView.animate(withDuration: 0.3) {
            self.alpha = 1
        }
    }
    
    func uploadFile(){
        print("upload")
        
        if fileURL != nil{
            
            progressBar.setProgress(0, animated: false)
            progressBar.alpha = 1
            uploadBtn.alpha = 0
            
            let decodedURL = fileURL?.absoluteString.removingPercentEncoding
            let fileName = decodedURL?.components(separatedBy: "/").last
            
            let fileData = try? Data(contentsOf: fileURL!)
            if fileData != nil && fileName != nil{
                
                var postData = Data()
                
                postData.append("--AaB03x\r\nContent-Disposition: form-data; name=\"printFile\"; filename=\"\(fileName!)\"\r\nContent-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
                postData.append(fileData!)
                postData.append("\r\n--AaB03x--\r\n".data(using: .utf8)!)
                
                var resq = URLRequest(url: URL(string: "\(baseDomainName)/print/?m=admin&c=goods&a=uploadfile")!)
                resq.httpMethod = "POST"
                resq.setValue("multipart/form-data; boundary=AaB03x", forHTTPHeaderField: "Content-Type")
                resq.setValue("\(postData.count)", forHTTPHeaderField: "Content-Length")
                print(resq.allHTTPHeaderFields ?? "nil")
                resq.httpBody = postData
                
                let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
                
                
                
                //id 3e332b3377e51d4de367a3a1a0fa152f
                uploadTask = session.dataTask(with: resq, completionHandler: { (data:Data?, er:URLResponse?, err:Error?) in
                    do{
                        print(String(data: data!, encoding: .utf8) ?? "data nil")
                        
                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        let code = jsonObj?.object(forKey: "code") as? Int
                        if code == 200 {
                            DispatchQueue.main.async {
                                self.uploadFinished(msg: jsonObj)
                            }
                        }else{
                            DispatchQueue.main.async {
                                self.uploadFailed(ex: jsonObj)
                            }
                        }
                    }catch let ex{
                        //                        let alert = UIAlertController(title: "上传失败", message: nil, preferredStyle: .alert)
                        //                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        //                        DispatchQueue.main.async {
                        //                            self.present(alert, animated: true, completion: nil)
                        //                        }
                        print(ex)
                        DispatchQueue.main.async {
                            self.uploadFailed(ex: ex)
                            
                        }
                    }
                })
                
                uploadTask!.resume()
                
            }
            
            
        }
        
        
        
        
        
        
    }
    
    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        DispatchQueue.main.async {
            self.progressBar.setProgress(Float(totalBytesSent)/Float(totalBytesExpectedToSend), animated: true)
        }
    }
    
    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }
    
    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
//        if fileURL == nil{
//            return URL(string: "file://\(DOCUMENT_PATH)/file.doc")! as QLPreviewItem
//        }
//        print(fileURL!)
//        print(fileURL!.absoluteString)
//        let filename = fileURL!.absoluteString.components(separatedBy: "/").last?.removingPercentEncoding
//        print(filename ?? "")
//        return URL(string: "file://\(DOCUMENT_PATH)/Inbox/\(filename ?? "file.doc")")! as QLPreviewItem
        return fileURL! as QLPreviewItem
//        return URL(string: "file://\(DOCUMENT_PATH)/Inbox/%E7%89%A9%E7%90%86%E5%AE%9E%E9%AA%8C%E8%AE%BE%E8%AE%A1%E5%A4%A7%E8%B5%9B%E9%80%9A%E7%9F%A5-5.doc")! as QLPreviewItem
    }
    
    func hideView(){
        if progressBar.alpha == 0{
            UIView.animate(withDuration: 0.3) {
                self.alpha = 0
            }
            delegate?.cardViewClose?(self)
        }else{
            let alert = UIAlertController(title: "退出文件上传", message: nil, preferredStyle: .actionSheet)
            alert.addAction(UIAlertAction(title: "退出", style: .destructive, handler: { (action) in
                self.uploadTask?.cancel()
                UIView.animate(withDuration: 0.3) {
                    self.alpha = 0
                }
                self.delegate?.cardViewClose?(self)
            }))
            alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            uploadDelegate?.fileUpload?(self, askBeforeExit: alert)
        }
        
    }
    
    func gotoFileView(){
        UIView.animate(withDuration: 0.3, animations: { 
            self.alpha = 0
        }) { (finish) in
//            self.uploadDelegate?.fileUpload?(self, gotoFileView: nil)
        }
        
    }
    
    func uploadFinished(msg: Any?){
        self.uploadDelegate?.fileUpload?(self, successUpload: msg)
        progressBar.alpha = 0
        finishBtn.alpha = 1
    }
    
    func uploadFailed(ex: Any?){
        self.uploadDelegate?.fileUpload?(self, failUpload: ex)
        progressBar.alpha = 0
        uploadBtn.alpha = 1
        
        let msg = (ex as? NSDictionary)?.object(forKey: "message") as? String
        if msg != nil{
            uploadBtn.setTitle("\(msg!), 点击重试", for: .normal)
        }else{
            uploadBtn.setTitle("点击重试", for: .normal)
        }
        
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
